from django.db.models import Q
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from task.models import Task
from task.serializers import TaskSerializers
from user.models import User, UserTask
from .models import Group
from .serializers import GroupSerializer
from datetime import datetime


class CustomPageNumberPagination(PageNumberPagination):
    # 设置分页类
    page_size_query_param = 'rows'


class GroupView(ModelViewSet):
    # 查询所有的组
    queryset = Group.objects.all()
    serializer_class = GroupSerializer
    pagination_class = CustomPageNumberPagination

    def list(self, request, *args, **kwargs):
        # 查询所有没有被删除组的信息
        queryset = self.get_queryset().filter(is_delete=False).order_by('create_time')
        # 分页
        paginte = self.paginate_queryset(queryset)
        if paginte is None:
            return Response(data={"results": []}, status=status.HTTP_200_OK)
        # 对结果序列化
        serializer = self.get_serializer(paginte, many=True)
        # 返回结果
        return self.get_paginated_response(serializer.data)

    def create(self, request, *args, **kwargs):
        """判断人员组名"""
        queryset = self.get_queryset().filter(name=request.data['name'], is_delete=False)
        if queryset:
            # 该组名已存在
            return Response(status=status.HTTP_400_BAD_REQUEST)

        return super().create(request, *args, **kwargs)

    def destroy(self, request, *args, **kwargs):
        """获取可删除的小组"""
        url = request.path
        group_id = url.rsplit("/")[-1]
        self.get_queryset().filter(id=group_id).update(is_delete=True, delete_time=datetime.now())
        return Response(status=status.HTTP_204_NO_CONTENT)

    # def update(self, request, *args, **kwargs):
    #     self.get_queryset().filter(id=request.data['id']).update(name=request.data['name'])
    #     return Response(status=status.HTTP_200_OK)

    @action(methods=['DELETE'], detail=False, url_path='batch-remove', url_name='batch-remove')
    def batch_remove(self, request, *args, **kwargs):
        # 人员组删除
        self.get_queryset().filter(pk__in=request.data).update(is_delete=True, delete_time=datetime.now())

        return Response(status=status.HTTP_204_NO_CONTENT)

    @action(methods=['GET'], detail=False, url_name='groupUpdateName', url_path='groupUpdateName')
    def groupUpdateName(self, request, *args, **kwargs):
        # 编辑组名称
        group_id = request.query_params.get('id')
        group = Group.objects.filter(id=group_id, is_delete=False)
        serialoze = GroupSerializer(group, many=True)
        return Response(data=serialoze.data, status=status.HTTP_200_OK)

    # 未知????
    # @action(methods=['GET'], detail=False, url_path='update-user', url_name='update-user')
    # def update_user(self, request, *args, **kwargs):
    #     #
    #     user = User.objects.all().filter(is_staff=False)
    #     serializer = self.get_serializer(user, many=True)
    #     return Response(data=serializer.data, status=status.HTTP_200_OK)

class CustomPageNumberPagination(PageNumberPagination):
    page_size_query_param = 'rows'  # 设置每页大小的查询参数名为 'rows'
    page_size = 10  # 默认每页显示的记录数（可选）
    max_page_size = 100  # 最大每页显示的记录数（可选）


# 分配任务
class GroupViewSet(ModelViewSet):
    # 该类是用于人员管理的分配任务
    # 查询所有的组
    queryset = Task.objects.all()   # 设置查询集，这里查询了所有的Task对象
    serializer_class = TaskSerializers   # 设置序列化器类
    # 分页
    pagination_class = CustomPageNumberPagination  # 设置分页类
    # PageNumberPagination.page_size_query_param = 'rows'

    def list(self, request, *args, **kwargs):
        # 获取查询参数
        stage_id = request.query_params.get('stage', None)
        module_id = request.query_params.get('module', None)
        level = request.query_params.get('level', None)
        search = request.query_params.get('search', None)

        # 获取未删除的任务
        queryset = self.get_queryset().filter(is_delete=False)

        # 根据查询参数动态添加过滤条件
        if stage_id is not None:
            queryset = queryset.filter(stage_id=stage_id)
            if module_id is not None:
                queryset = queryset.filter(module_id=module_id)
        if level is not None:
            queryset = queryset.filter(level=level)
        # 关键字过滤
        if search:
            queryset = queryset.filter(Q(title__icontains=search))
        # 进行分页
        paginate = self.paginate_queryset(queryset)
        if paginate is None:
            return Response(data={"message": "请求必须进行分页"}, status=status.HTTP_400_BAD_REQUEST)
        serializer = self.get_serializer(paginate, many=True)
        # 返回分页之后的结果
        return self.get_paginated_response(serializer.data)


#######给用户添加任务 核心方法
    @action(methods=['POST'],detail=False,url_path='assign-task',url_name='assign-task')
    def assign_task(self,request,*args,**kwargs):
        #### 给用户添加任务

        data=request.data
        group_id =data.get('group_id')#获取要分配的任务的在组id
        task_Id_list = data.getlist('rows[]')# 获取要分配任务 的id

        #根据组 group_id获取当前组中的用户
        group=Group.objects.get(id=group_id)  #根据group_id 查找该组
        if group is None:
            return Response(data={'message':'该组不存在,无法添加任务'},status=status.HTTP_404_NOT_FOUND)

        users=group.users.all() #获取当前组中的所有用户
        #遍历用户列表，为每个用户分配任务
        for user in users:
            for task_id in task_Id_list:
                task=Task.objects.get(id=task_id)
                UserTask.objects.create(
                    user=user,
                    task=task,
                    create_time=datetime.now(),
                    task_state=0,  ##定义默认的状态是0
                )
        return Response(data={'message': '任务分配成功'}, status=status.HTTP_200_OK)